library(stringr)
library(plyr)
library(xtable)

options(xtable.caption.placement = 'top', # notice \floatsetup overrides
		xtable.comment = FALSE,
		xtable.booktabs = TRUE)


data <- read_csv("study1.csv")

ptp <- function(df, var, lab, cap){
	
	tempt <- xtable(prop.table(table(df[,var])
	),
	caption=cap)
	
	names(tempt) <- lab
	
	print(tempt,
		  type="latex")
}

ptm <- function(df, var, lab, cap){
	tempt <- xtable(as.data.frame(
		mean(df[,var],
			 na.rm=T)
	),
	caption=cap)
	
	names(tempt) <- lab
	print(tempt,
		  include.rownames=FALSE,
		  type="latex")
}

recode_demographics <- function(df, gender, race, partisanship, income, education, age){
	df$gender[df[, gender] == 2] <- "Female"
	df$gender[df[, gender] == 1] <- "Male"
	df$gender <- as.factor(df$gender)
	
	df$race[df[,race]==1] <- "White/Caucasian"
	df$race[df[,race]==2] <-"African American"
	df$race[df[,race]==3] <-"Hispanic"
	df$race[df[,race]==4] <-"Asian"
	df$race[df[,race]==5] <-"Native American"
	df$race[df[,race]==6] <-"Pacific Islander"
	df$race[df[,race]==7] <-"Other"
	df$race <- as.factor(df$race)
	
	df$pid <- NA
	df$pid[df[,partisanship]==1] <- "Democrat"
	df$pid[df[,partisanship]==2] <- "Republican"
	df$pid[df[,partisanship]==3] <- "Independent"
	df$pid[df[,partisanship]==4] <- "Other"
	
	df$income <- NA
	df$income[df[,income]==1] <- "Less than 30,000"
	df$income[df[,income]==2] <- "30,000 – 39,999"
	df$income[df[,income]==3] <- "40,000 – 49,999"
	df$income[df[,income]==4] <- "50,000 – 59,999"
	df$income[df[,income]==5] <- "60,000 – 69,999"
	df$income[df[,income]==6] <- "70,000 – 79,999"
	df$income[df[,income]==7] <- "80,000 – 89,999"
	df$income[df[,income]==8] <- "90,000 – 99,999"
	df$income[df[,income]==9] <- "100,000 or more"
	df$income <- as.factor(df$income)
	
	df$education <- NA
	df$education[df[,education]==1] <- "Less than High School"
	df$education[df[,education]==2] <- "High School / GED"
	df$education[df[,education]==3] <- "Some College"
	df$education[df[,education]==4] <- "2-year College Degree"
	df$education[df[,education]==5] <- "4-year College Degree"
	df$education[df[,education]==6] <- "Masters Degree"
	df$education[df[,education]==7] <- "Doctoral Degree"
	df$education[df[,education]==8] <- "Professional Degree (JD, MD)"
	df$education <- as.factor(df$education)
	
	df$age <- df[,age] + 16
	
	return(df)
}

print_demographics <- function(df){
	ptp(df, "gender", "%", "Gender")
	ptp(df, "race", "%", "Race/Ethnicity")
	ptp(df, "pid", "%", "Partisanship")
	ptp(df, "income", "%", "Income")
	ptp(df, "education", "%", "Education")
	ptm(df, "age", "Mean", "Age")
}

data$Q9[data$Q10==1] <- 1
data$Q9[data$Q10==2] <- 2
data <- data[data$Q9 <=2,]
data <- data[data$Q9 <=2,]

data <- data[data$Q5 <=2,]

data <- recode_demographics(df =data, gender ="Q4", race= "Q5", partisanship = "Q9", income= "Q6", education="Q7",age="Q13")

mean(data$Q13+2, na.rm=T)

print_demographics(data)

